package com.beamfield.controller.api.mb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beamfield.common.*;
import com.beamfield.controller.common.MbBaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.AdminInfo;
import com.beamfield.model.Leave;
import com.beamfield.model.ManagerInfo;
import com.beamfield.model.NormalOperator;
import com.beamfield.model.SpecialOperator;
import com.beamfield.modelVo.BatchAttendMonthVo;
import com.beamfield.modelVo.Qrcode;
import com.beamfield.service.manage.auth.AdminInfoService;
import com.beamfield.service.manage.operator.AttendService;
import com.beamfield.service.manage.operator.ManagerInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @author chenjj
 * @Description:
 * @Date 2018/10/10
 */
@Controller
@RequestMapping(value = "/mb_api/managerInfo")
public class MbManagerInfoController extends MbBaseController{
    private final ManagerInfoService managerInfoService;

    private final AttendService attendService;

    private final AdminInfoService adminInfoService;

    @Autowired
    public MbManagerInfoController(ManagerInfoService managerInfoService,AttendService attendService,AdminInfoService adminInfoService){
        this.managerInfoService = managerInfoService;
        this.attendService = attendService;
        this.adminInfoService = adminInfoService;
    }
    /**
     * 获取登录用户信息
     * @return
     */
    @RequestMapping(value = "/getLoginInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getLoginInfo(HttpServletRequest request){
        Long userId = super.getLogInfo(request).getUserId();
        try{
            return adminInfoService.getLoginInfo(userId);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 获取组织架构班组数据
     * @return
     */
    @RequestMapping(value = "/getGroupData", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getGroupDate(HttpServletRequest request){
        Long beamId = super.getLogInfo(request).getBeamId();
        try{
            return managerInfoService.getMbGroupData(beamId);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 获取人员列表
     * @return
     */
    @RequestMapping(value = "/getPeopleList", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getPeopleList(HttpServletRequest request){
        Long beamId = super.getLogInfo(request).getBeamId();

        JSONObject jsonObject = super.getBody(request);
        if(jsonObject == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        Integer offset = jsonObject.getInteger("offset");
        Integer limit = jsonObject.getInteger("limit");
        String name = jsonObject.getString("name");
        String presasg = jsonObject.getString("presasg");
        String workdept = jsonObject.getString("workdept");
        String group = jsonObject.getString("group");

        try{
            PageResult peoplePage = null;
            if(StringUtils.isEmpty(group)){
                peoplePage = managerInfoService.getManagerInfoList(offset,limit,null,name,beamId,presasg,workdept);
            }
            else {
                peoplePage = managerInfoService.mergeOperatorList(offset,limit,null,name,beamId,null,group);
            }
            return new ApiResult(peoplePage);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 获取人员基本信息详情
     * @return
     */
    @RequestMapping(value = "/getPeopleInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getPeopleInfo(HttpServletRequest request){
        Long beamId = super.getLogInfo(request).getBeamId();

        JSONObject jsonObject = super.getBody(request);
        if(jsonObject == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        String eCode = jsonObject.getString("eCode");
        if(StringUtils.isEmpty(eCode)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }

        try{
            if(eCode.startsWith("01")){
                Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
                ManagerInfo peopleInfo = managerInfoService.getMbManagerInfo(peopleId,beamId);
                return new ApiResult(peopleInfo);
            }
            else if(eCode.startsWith("02")){
                Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
                SpecialOperator peopleInfo = managerInfoService.getMbSpecialOperatorInfo(peopleId,beamId);
                return new ApiResult(peopleInfo);
            } else if(eCode.startsWith("03")) {
                Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
                NormalOperator peopleInfo = managerInfoService.getMbNormalOperatorInfo(peopleId,beamId);
                return new ApiResult(peopleInfo);
            }else{
                Long userId = super.getUserId(request);
                AdminInfo adminInfo = (AdminInfo) adminInfoService.getLoginInfo(userId).getResult();
                ManagerInfo managerInfo = new ManagerInfo();
                managerInfo.setName(adminInfo.getReal_name());
                managerInfo.setEcode(adminInfo.getEcode());
                managerInfo.setPhone(adminInfo.getMobile());
                return new ApiResult(managerInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }
    
    /**
     * 获取人员基本信息详情
     * @return
     */
    @RequestMapping(value = "/getLoginAdminInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getLoginAdminInfo(HttpServletRequest request){
        Long beamId = super.getLogInfo(request).getBeamId();
        Long userId = super.getLogInfo(request).getUserId();
        ApiResult res = adminInfoService.getLoginInfo(userId);
		AdminInfo adminInfo = (AdminInfo) res.getResult();
        try{
        	if(adminInfo!=null) {
        		String eCode = adminInfo.getEcode();
        		if(eCode.startsWith("01")){
                    Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
                    ManagerInfo peopleInfo = managerInfoService.getMbManagerInfo(peopleId,beamId);
                    return new ApiResult(peopleInfo);
                }
                else if(eCode.startsWith("02")){
                    Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
                    SpecialOperator peopleInfo = managerInfoService.getMbSpecialOperatorInfo(peopleId,beamId);
                    return new ApiResult(peopleInfo);
                } else if(eCode.startsWith("03")) {
                    Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
                    NormalOperator peopleInfo = managerInfoService.getMbNormalOperatorInfo(peopleId,beamId);
                    return new ApiResult(peopleInfo);
                }else{
                    ManagerInfo managerInfo = new ManagerInfo();
                    managerInfo.setName(adminInfo.getReal_name());
                    managerInfo.setEcode(adminInfo.getEcode());
                    managerInfo.setPhone(adminInfo.getMobile());
                    return new ApiResult(managerInfo);
                }
    		}
        	return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage()); 
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 获取人员培训
     * @return
     */
    @RequestMapping(value = "/getPeopleTrainList", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getPeopleTrainList(HttpServletRequest request){
        JSONObject jsonObject = super.getBody(request);
        if(jsonObject == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        Integer offset = jsonObject.getInteger("offset");
        Integer limit = jsonObject.getInteger("limit");
        String eCode = jsonObject.getString("eCode");
        if(StringUtils.isEmpty(eCode)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try{
            PageResult peopleTrainPage = null;
            Long peopleId = managerInfoService.getPeopleIdByEcode(eCode);
            if(eCode.startsWith("01")){
                peopleTrainPage = managerInfoService.getDetailManagerTrainList(offset,limit,peopleId);
            } else if(eCode.startsWith("02")){
                peopleTrainPage = managerInfoService.getDetailSpecialOperatorList(offset,limit,peopleId);
            } else if(eCode.startsWith("03")){
                peopleTrainPage = managerInfoService.getDetailNormalOperatorList(offset,limit,peopleId);
            }
            return new ApiResult(peopleTrainPage);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 获取指定月份人员考勤记录
     * @return
     */
    @RequestMapping(value = "/getPeopleAttendByMonth", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getPeopleAttendByMonth(HttpServletRequest request){
        Long beamId = super.getLogInfo(request).getBeamId();

        JSONObject jsonObject = super.getBody(request);
        if(jsonObject == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        String eCode = jsonObject.getString("eCode");
        String month = jsonObject.getString("month");
        if(StringUtils.isEmpty(eCode) || StringUtils.isEmpty(month)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try{
            if(eCode.startsWith("04")){
                return new ApiResult();
            }
//            BatchAttendMonthVo peopleAttend = attendService.getBatchAttendMonthVo(eCode,beamId,month).get(0);
            List<BatchAttendMonthVo> attend = attendService.getAttendMonth(eCode,beamId,month);
            BatchAttendMonthVo peopleAttend = new BatchAttendMonthVo();
            if(attend.size()>0) {
            	peopleAttend  = attend.get(0);
            }
            return new ApiResult(peopleAttend);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 根据二维码信息获取人员信息
     * @return
     */
    @RequestMapping(value = "/getPeopleInfoByQrcode", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getDeviceInfo(HttpServletRequest request){
        Long beamId = super.getLogInfo(request).getBeamId();

        JSONObject body = super.getBody(request);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        String qrCodeJson = body.getString("qrCodeJson");
        Qrcode qrcode = super.getQrcode(qrCodeJson);
        if(qrcode == null){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "无法解析二维码信息");
        }
        if(!Objects.equals(qrcode.getBeam(), String.valueOf(beamId))){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "此二维码不属于当前登录梁场");
        }
        try{
            String type = qrcode.getType();
            Long peopleId = Long.parseLong(qrcode.getData());
            if("1".equals(type)){
                return new ApiResult(managerInfoService.getMbManagerInfo(peopleId,beamId));
            }
            else if("2".equals(type)){
                return new ApiResult(managerInfoService.getMbSpecialOperatorInfo(peopleId,beamId));
            }
            else {
                return new ApiResult(managerInfoService.getMbNormalOperatorInfo(peopleId,beamId));
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }
    
    /**
	 * 保存人员请假信息
	 *
	 * @param leaveJson
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveLeave", method = RequestMethod.POST)
	public ApiResult saveLeave(HttpServletRequest request) {
		JSONObject body = super.getBody(request);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
		Long beamId = super.getLogInfo(request).getBeamId();
		Long userId = super.getLogInfo(request).getUserId();
		try {
			String reason = body.getString("reason");
			String starttime = body.getString("starttime");
			String endtime = body.getString("endtime");
			String content = body.getString("content");
			String pic = body.getString("pic");
			String startCity = body.getString("startCity");
			String endCity = body.getString("endCity");
			Leave leave = new Leave();
			ApiResult res = adminInfoService.getLoginInfo(userId);
			AdminInfo admin = (AdminInfo) res.getResult();
			if(admin!=null) {
				ManagerInfo manager = managerInfoService.getManagerByEcodeAndBeamId(beamId, admin.getEcode());
				if(manager!=null) {
					leave.setName(manager.getName());
				}else {
					leave.setName(admin.getReal_name());
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			    leave.setStarttime(sdf.parse(starttime));
			    leave.setEndtime(sdf.parse(endtime));
			    if(pic!=null) {
			    	leave.setPicId(CommonUtils.parseLong(pic, 0));
			    }
				if(startCity!=null) {
					leave.setStartCity(startCity);
				}
				if(endCity!=null) {
					leave.setEndCity(endCity);
				}
				leave.setContent(content);
				leave.setBeam_id(beamId);
				leave.setEcode(admin.getEcode());
				leave.setOperator(userId);
				leave.setAddtime(new Date());
				leave.setUpdatetime(new Date());
				leave.setReason(reason);
			}
 			return managerInfoService.saveLeave(leave,beamId,userId);
		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
	}
}